package com.graph;

public class Solution1254 {
    public int closedIsland(int[][] grid) {
        int res = 0;
        boolean[][] visited = new boolean[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 0) {
                    res += dfs(grid, visited, i, j);
                }
            }
        }
        return res;
    }

    public int dfs(int[][] grid, boolean[][] visited, int i, int j) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return 0;
        if (visited[i][j] || grid[i][j] == 1) return 1;
        grid[i][j] = 2;
        visited[i][j] = true;
        int a = dfs(grid, visited, i + 1, j);
        int b = dfs(grid, visited, i - 1, j);
        int c = dfs(grid, visited, i, j + 1);
        int d = dfs(grid, visited, i, j - 1);
        if (a + b + c + d != 4) return 0;
        return 1;
    }
}
